package http;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.FileUtils;


import com.blankj.utilcode.util.ActivityUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class Api {
    public ApiService service;
    private static final int MAXNUMBER = 9999;

    private FileUtils.ProgressListener progressListener;

    private Retrofit retrofit;

    private OkHttpClient initOkHttpClicent() {

// 缓存路径- app 缓存目录
        File file = new File(ActivityUtils.getTopActivity().getFilesDir(), "bbb");
        Cache cache = new Cache(file,
                10 * 1024 * 1024); // 10 MB


        return new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        if (!isNetworkConnected()) {
                            // 无网络时强制从缓存读取，如果缓存中没有数据会返回 504
                            // FORCE_CACHE 里设置了 only-if-cached==true 和 maxStale
                            // only-if-cached 顾名思义就是只有缓存中有数据才返回，没有时返回 504
                            // maxStale 指可以取过期多久的数据，FORCE_CACHE 中设置为了Int最大值
                            request = request.newBuilder()
                                    .cacheControl(CacheControl.FORCE_CACHE)
                                    .build();
                        } else {
                            // 有网络时从网络获取
                            // FORCE_NETWORK 里设置了 no-cache
                            // no-cache 顾名思义，强制客户端直接向服务器发送请求,也就是说每次请求都必须向服务器发送。服务器接收到请求，然后判断资源是否变更，是则返回新内容，否则返回304(Not Modified)。
                            // 注意服务器根据 Etag 判断资源未变更时返回的是 304，这时还是从缓存中拿，这里有点违背 no-cache 的含义，要注意理解。
                            request = request.newBuilder()
                                    .cacheControl(CacheControl.FORCE_NETWORK)
                                    .build();
                        }
                        return chain.proceed(request);
                    }
                })
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response response = chain.proceed(chain.request());

                        // 缓存 10 秒
                        CacheControl cacheControl = new CacheControl.Builder()
                                .maxAge(10, TimeUnit.SECONDS)

                                .build();

                        return response.newBuilder()
                                .removeHeader("Pragma")
                                .header("Cache-Control", cacheControl.toString())

                                .build();
                    }
                })
                .cache(cache)

                //这两个配置不能乱加， 忽视证书的 不安全
                .sslSocketFactory(SSLSocketManager.getSSLSocketFactory())//配置
                .hostnameVerifier(SSLSocketManager.getHostnameVerifier())//配置
                .addInterceptor(new QHttpInterceptor())
                .build();










//
//        return new OkHttpClient.Builder()
//                .connectTimeout(30, TimeUnit.SECONDS).
//                        readTimeout(30, TimeUnit.SECONDS).
//                        writeTimeout(30, TimeUnit.SECONDS)
//                .addInterceptor(new QHttpInterceptor())
//
//
//
//
//
//                //这两个配置不能乱加， 忽视证书的 不安全
//                .sslSocketFactory(SSLSocketManager.getSSLSocketFactory())//配置
//                .hostnameVerifier(SSLSocketManager.getHostnameVerifier())//配置
//                .build();


    }



    public Api() {

        retrofit = new Retrofit.Builder()
              .baseUrl("http://192.168.1.22")
                .addConverterFactory(GsonConverterFactory.create())
                .client(initOkHttpClicent())
                .build();

        service = retrofit.create(ApiService.class);
    }


   private boolean isNetworkConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) ActivityUtils.getTopActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }


    public static Api api;

    public static synchronized Api getInstance() {
        if (api == null) {
            api = new Api();
        }
        return api;
    }


}
